package net.linku.config.resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;

/**
 * 资源服务器配置类，配置资源服务的安全访问策略和JWT令牌解析。
 */
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    /**
     * 配置HTTP安全策略，包括允许的路径和认证要求。
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                // 禁用CSRF，因为使用JWT令牌不需要CSRF保护
                .csrf().disable()
                // 禁用session管理，因为基于token，不需要HTTP session
                .sessionManagement().disable()
                .authorizeRequests().antMatchers(
                "/account/login",
                "/register",
                "/gt/register",
                "/v2/api-docs",
                "/swagger-resources/configuration/ui",  // Swagger UI配置
                "/swagger-resources",                    // 获取api-docs的URI
                "/swagger-resources/configuration/security",  // 安全选项
                "/webjars/**",
                "/swagger-ui.html"
        ).permitAll()
                .antMatchers("/**").authenticated()
                .and().headers().cacheControl();
    }

    /**
     * 配置资源服务器的安全性，设置JWT令牌存储。
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
    }

    /**
     * 创建一个JWT令牌存储实例。
     *
     * @return JWT令牌存储实例
     */
    @Bean
    public TokenStore tokenStore() {
        JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter());
        return jwtTokenStore;
    }

    /**
     * 创建一个JWT访问令牌转换器，并设置公钥验证器。
     *
     * @return JWT访问令牌转换器
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        ClassPathResource classPathResource = new ClassPathResource("linku.pub");
        String publicKey = null;
        try {
            byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
            publicKey = new String(bytes, "utf-8");
        } catch (IOException e) {
            log.error("读取公钥失败");
        }
        tokenConverter.setVerifierKey(publicKey);
        return tokenConverter;
    }
}
